import { _decorator, Component, Label } from 'cc';
import { Game } from '../core/Game';
import { Databus } from '../core/Databus';
import { EventManager } from '../core/EventManager';
import { updateSetting } from '../services/Setting';
import DataEventReport from '../platform/DataEventReport';
const { ccclass, property } = _decorator;
const databus = Databus.Instance();
@ccclass('EndlessBattleLogic')
export class EndlessBattleLogic extends Component {
  private continueHitBallCount = 0;
  private maxContinueHitBall = 0;
  protected onLoad(): void {
    EventManager.Instance().AddEventListener('AddUserScore', this, this.addUserScore);
    EventManager.Instance().AddEventListener('ChangeUserHitBall', this, this.changeUserHitBall);
  }
  start() {
    this.continueHitBallCount = 0;
    this.maxContinueHitBall = databus.maxContinueHitBall;
    if (Game.Instance().battleCate.isEndlessBattle()) {
      this.node.active = true;
    } else {
      this.node.active = false;
    }
  }
  public update(deltaTime: number) {
    this.updateEndlessText();
  }
  public addUserScore(name: string, data: {side: number, score: number}) {
    if (!Game.Instance().battleCate.isEndlessBattle()) {
      return;
    }
    if (data.score > 0) {
      this.continueHitBallCount += data.score;
      this.updateMaxContinueHitBall();
    }
  }
  public changeUserHitBall() {
    if (Game.Instance().battleCate.isEndlessBattle()) {
      if (this.continueHitBallCount >= this.maxContinueHitBall) {
        this.maxContinueHitBall = this.continueHitBallCount;
      }
      this.continueHitBallCount = 0;

      DataEventReport.Instance().reportCoreMetric(
        'endless', Game.Instance().battleCate.valueBattle(),
        Game.Instance().gameType.valueType(),
      );
      return;
    }
  }
  public updateEndlessText() {
    this.node.getChildByName('ContinueHitBall').getChildByName('LabelCount').getComponent(Label).string = `${this.continueHitBallCount}`;
    this.node.getChildByName('MaxContinueHitBall').getChildByName('LabelCount').getComponent(Label).string = `${this.maxContinueHitBall}`;
  }
  private updateMaxContinueHitBall() {
    if (this.continueHitBallCount > databus.maxContinueHitBall) {
      updateSetting(databus.selfInfo.userId, databus.selfInfo.userId, 3, 'maxContinueHitBall', `${this.continueHitBallCount}`);
      databus.maxContinueHitBall = this.continueHitBallCount;
    }
  }
}

